package com.like.hospitalworld;

import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.like.dialog.ShareDialogFragment;
import com.like.entity.Department;
import com.like.entity.EventWrapper;
import com.like.entity.GeneralResponse;
import com.like.entity.InfoCollectReq;
import com.like.entity.InfoDetailResp;
import com.like.entity.InfoGetReplyResp;
import com.like.entity.InfoListResp;
import com.like.entity.InfoReplyReq;
import com.like.fragment.InfoDetailContentFragment;
import com.like.fragment.InfoDetailReplyFragment;
import com.like.likeutils.device.KeyBoardUtils;
import com.like.likeutils.network.RetrofitCallback;
import com.like.network.InfoService;
import com.like.network.ResponseCode;
import com.like.network.RetrofitUtil;
import com.like.utils.Constants;
import com.like.widget.MyToast;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import retrofit2.Call;
import retrofit2.Response;

@ContentView(R.layout.activity_info_detail)
public class InfoDetailActivity extends BaseActivity {

    public static final int REQUEST_INFO_BASE = 100;
    public static final int REQUEST_INFO_DATA = 101;
    public static final int REQUEST_INFO_REPLY = 102;
    public static final int REQUEST_CLOSE_COMMENT = 103;

    @ViewInject(R.id.comment_real_container)
    private RelativeLayout mCommentRealContainer;
    @ViewInject(R.id.comment_container)
    private FrameLayout mCommentContainer;
    @ViewInject(R.id.edit_comment_real)
    private EditText mEditCommentReal;
    @ViewInject(R.id.edit_comment)
    private EditText mEditComment;
    @ViewInject(R.id.child_container)
    private ViewGroup mChildContainer;
    @ViewInject(R.id.title)
    private TextView mTitle;
    @ViewInject(R.id.collection_img)
    private ImageView mCollectionImg;
    @ViewInject(R.id.unread_count)
    private TextView mUnreadCount;

    private InfoDetailContentFragment mContentFragment;
    private InfoDetailReplyFragment mReplyFragment;
    private InfoListResp.InformationBase mInfo;
    private InfoService mInfoService;
    private InfoDetailResp mInfoDetailResp;
    private InfoGetReplyResp.InformationComment mCurrentComment;
    private ShareDialogFragment mShareDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        initFragments();
        showContent();
        initTitle();
        mShareDialog = new ShareDialogFragment();
        mShareDialog.setInfoId(mInfo.id);
        mInfoService = RetrofitUtil.getService(InfoService.class);
        mEditComment.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    openComment();
                }
            }
        });
        mEditCommentReal.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    closeComment(false);
                }
            }
        });
    }

    private void openComment() {
        mCommentContainer.setVisibility(View.GONE);
        mCommentRealContainer.setVisibility(View.VISIBLE);
        mEditCommentReal.requestFocus();
        KeyBoardUtils.openKeybord(mEditCommentReal, m.mContext);
    }

    private void closeComment(boolean clearText) {
        KeyBoardUtils.closeKeybord(mEditCommentReal, m.mContext);
        mCommentContainer.setVisibility(View.VISIBLE);
        mCommentRealContainer.setVisibility(View.GONE);
        if (clearText) {
            mEditCommentReal.setText("");
            mEditCommentReal.setHint("回复：");
        }
    }

    private void initCollect(InfoDetailResp infoDetail) {
        if (infoDetail == null)
            return;
        mCollectionImg.setSelected(infoDetail.isCollect);
    }

    private void initTitle() {
        Department dep = m.getCurrentDep();
        if (dep != null) {
            mTitle.setText(dep.name + "资讯");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(sticky = true)
    public void onGetStickyEvent(EventWrapper event) {
        if (EventWrapper.isMatch(event, getClass(), REQUEST_INFO_BASE)) {
            mInfo = (InfoListResp.InformationBase) event.data;
        }
    }

    @Subscribe
    public void onGetEvent(EventWrapper event) {
        if (EventWrapper.isMatch(event, getClass(), REQUEST_INFO_DATA)) {
            mInfoDetailResp = (InfoDetailResp) event.data;
            if (mInfoDetailResp.noReadNum == 0)
                mUnreadCount.setVisibility(View.GONE);
            else {
                mUnreadCount.setVisibility(View.VISIBLE);
                mUnreadCount.setText(mInfoDetailResp.noReadNum + "");
            }
            initCollect(mInfoDetailResp);
        }
        if (EventWrapper.isMatch(event, getClass(), REQUEST_INFO_REPLY)) {
            mCurrentComment = (InfoGetReplyResp.InformationComment) event.data;
            mEditCommentReal.setHint("回复：" + mCurrentComment.ickname);
            mEditComment.requestFocus();
        }
        if (EventWrapper.isMatch(event, getClass(), REQUEST_CLOSE_COMMENT)) {
            String comment = mEditCommentReal.getText().toString();
            closeComment(TextUtils.isEmpty(comment));
        }
    }

    private void initFragments() {
        mContentFragment = new InfoDetailContentFragment();
        mContentFragment.setInfoBase(mInfo);
        mReplyFragment = new InfoDetailReplyFragment();
        mReplyFragment.setInfoBase(mInfo);
    }

    @Event(R.id.share)
    private void shareClick(View v) {
        mShareDialog.show(getSupportFragmentManager(), "share_dialog");
    }

    @Event(R.id.replies)
    private void showReplyClick(View v) {
        showReply();
    }

    @Event(R.id.send_reply)
    private void replyClick(View v) {
        String comment = mEditCommentReal.getText().toString();
        if (TextUtils.isEmpty(comment)) {
            MyToast.showBlueCircleToast(m.mContext, "请输入评论");
            return;
        }
        int subId = 0;
        if (mCurrentComment != null)
            subId = mCurrentComment.id;
        InfoReplyReq req = new InfoReplyReq(mInfo.id, m.getLoginResp().userID, comment, subId);
        Call<GeneralResponse<Object>> call = mInfoService.reply(Constants.getGUID(), m.getToken(), req);
        call.enqueue(new RetrofitCallback<GeneralResponse<Object>>() {
            @Override
            public void onResponse(Call<GeneralResponse<Object>> call, Response<GeneralResponse<Object>> response) {
                mCurrentComment = null;
                mEditCommentReal.setHint("回复：");
                mEditCommentReal.setText("");
                if (!response.isSuccessful())
                    return;
                GeneralResponse resp = response.body();
                if (resp.result == ResponseCode.SUCCESS) {
                    MyToast.showBlueCircleToast(m.mContext, "评论成功");
                    mChildContainer.requestFocus();
                    mReplyFragment.getReply(0, false);
                } else {
                    MyToast.showBlueCircleToast(m.mContext, "评论失败");
                }
            }

            @Override
            public void onFailure(Call<GeneralResponse<Object>> call, Throwable t) {
                t.printStackTrace();
            }
        });
    }

    @Event(R.id.collection)
    private void collectionClick(View v) {
        if (mInfoDetailResp == null)
            return;
        InfoCollectReq req = new InfoCollectReq(m.getLoginResp().userID, mInfo.id, !mInfoDetailResp.isCollect);
        Call<GeneralResponse<Object>> call = mInfoService.collect(Constants.getGUID(), m.getToken(), req);
        call.enqueue(new RetrofitCallback<GeneralResponse<Object>>() {
            @Override
            public void onResponse(Call<GeneralResponse<Object>> call, Response<GeneralResponse<Object>> response) {
                if (!response.isSuccessful())
                    return;
                GeneralResponse res = response.body();
                if (res.result == ResponseCode.SUCCESS) {
                    if (mInfoDetailResp.isCollect)
                        MyToast.showBlueCircleToast(m.mContext, "取消收藏成功");
                    else
                        MyToast.showBlueCircleToast(m.mContext, "收藏成功");
                    mInfoDetailResp.isCollect = !mInfoDetailResp.isCollect;
                    mCollectionImg.setSelected(mInfoDetailResp.isCollect);
                } else {
                    Toast.makeText(m.mContext, "收藏失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<GeneralResponse<Object>> call, Throwable t) {
                t.printStackTrace();
            }
        });
    }

    private void showContent() {
        if (mContentFragment.isAdded() || mContentFragment.isVisible())
            return;
        if (mReplyFragment.isAdded() && mReplyFragment.isVisible())
            getSupportFragmentManager().beginTransaction().replace(R.id.content_container, mContentFragment).commit();
        else
            getSupportFragmentManager().beginTransaction().add(R.id.content_container, mContentFragment).commit();
    }

    private void showReply() {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        if (mReplyFragment.isAdded() || mReplyFragment.isVisible())
            return;
        if (mContentFragment.isAdded() && mContentFragment.isVisible()) {
            transaction.addToBackStack(null);
            transaction.replace(R.id.content_container, mReplyFragment);
            transaction.commit();
        } else
            getSupportFragmentManager().beginTransaction().add(R.id.content_container, mReplyFragment).commit();
    }
}
